package com.inphase.myfood_client.util;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * HttpClient 工具类
 * 
 * @author Tangxuebing
 * 
 */
public class HttpUtils {
	private static JSONObject json = null;
	private static HttpClient client = null;
	private static HttpGet httpGet = null;
	private static HttpResponse response = null;
	private static HttpEntity entity = null;

	/**
	 * 将uri 返回的结果 封装为 json对象
	 * 
	 * @param uri
	 * @return
	 */
	public static JSONObject getJsonObject(String urlStr) {
		client = new DefaultHttpClient();
		System.out.println(urlStr);

		try {
			httpGet = new HttpGet(urlStr);
			response = client.execute(httpGet);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				entity = response.getEntity();
				String resultStr = EntityUtils.toString(entity);
				System.out.println("resultStr :" + resultStr);
				json = new JSONObject(resultStr);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} finally {
			if (client != null) {
				client.getConnectionManager().shutdown();
			}
		}
		return json;
	}

}
